//===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2024 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//

// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto-codegenerator.
// DO NOT EDIT.

#if canImport(FoundationEssentials)
import FoundationEssentials
#else
import Foundation
#endif
@_exported import SotoCore

/// Service object for interacting with AWS TimestreamQuery service.
///
/// Amazon Timestream Query
public struct TimestreamQuery: AWSService {
    // MARK: Member variables

    /// Client used for communication with AWS
    public let client: AWSClient
    /// Service configuration
    public let config: AWSServiceConfig
    /// endpoint storage
    @usableFromInline 
    let endpointStorage: AWSEndpointStorage

    // MARK: Initialization

    /// Initialize the TimestreamQuery client
    /// - parameters:
    ///     - client: AWSClient used to process requests
    ///     - region: Region of server you want to communicate with. This will override the partition parameter.
    ///     - partition: AWS partition where service resides, standard (.aws), china (.awscn), government (.awsusgov).
    ///     - endpoint: Custom endpoint URL to use instead of standard AWS servers
    ///     - middleware: Middleware chain used to edit requests before they are sent and responses before they are decoded 
    ///     - timeout: Timeout value for HTTP requests
    ///     - byteBufferAllocator: Allocator for ByteBuffers
    ///     - options: Service options
    public init(
        client: AWSClient,
        region: SotoCore.Region? = nil,
        partition: AWSPartition = .aws,
        endpoint: String? = nil,
        middleware: AWSMiddlewareProtocol? = nil,
        timeout: TimeAmount? = nil,
        byteBufferAllocator: ByteBufferAllocator = ByteBufferAllocator(),
        options: AWSServiceConfig.Options = []
    ) {
        self.client = client
        self.config = AWSServiceConfig(
            region: region,
            partition: region?.partition ?? partition,
            amzTarget: "Timestream_20181101",
            serviceName: "TimestreamQuery",
            serviceIdentifier: "query.timestream",
            signingName: "timestream",
            serviceProtocol: .json(version: "1.0"),
            apiVersion: "2018-11-01",
            endpoint: endpoint,
            errorType: TimestreamQueryErrorType.self,
            middleware: middleware,
            timeout: timeout,
            byteBufferAllocator: byteBufferAllocator,
            options: options
        )
        self.endpointStorage = .init()
    }





    // MARK: API Calls

    ///  Cancels a query that has been issued. Cancellation is provided only if the query has not completed running before the cancellation request was issued. Because cancellation is an idempotent operation, subsequent cancellation requests will return a CancellationMessage, indicating that the query has already been canceled. See code sample for details.
    @Sendable
    @inlinable
    public func cancelQuery(_ input: CancelQueryRequest, logger: Logger = AWSClient.loggingDisabled) async throws -> CancelQueryResponse {
        try await self.client.execute(
            operation: "CancelQuery", 
            path: "/", 
            httpMethod: .POST, 
            serviceConfig: self.config
                .with(middleware: EndpointDiscoveryMiddleware(storage: self.endpointStorage, discover: self.getEndpoint, required: true)
            ), 
            input: input, 
            logger: logger
        )
    }
    ///  Cancels a query that has been issued. Cancellation is provided only if the query has not completed running before the cancellation request was issued. Because cancellation is an idempotent operation, subsequent cancellation requests will return a CancellationMessage, indicating that the query has already been canceled. See code sample for details.
    ///
    /// Parameters:
    ///   - queryId:  The ID of the query that needs to be cancelled. QueryID is returned as part of the query result.
    ///   - logger: Logger use during operation
    @inlinable
    public func cancelQuery(
        queryId: String,
        logger: Logger = AWSClient.loggingDisabled        
    ) async throws -> CancelQueryResponse {
        let input = CancelQueryRequest(
            queryId: queryId
        )
        return try await self.cancelQuery(input, logger: logger)
    }

    ///  Create a scheduled query that will be run on your behalf at the configured schedule. Timestream assumes the execution role provided as part of the ScheduledQueryExecutionRoleArn parameter to run the query. You can use the NotificationConfiguration parameter to configure notification for your scheduled query operations.
    @Sendable
    @inlinable
    public func createScheduledQuery(_ input: CreateScheduledQueryRequest, logger: Logger = AWSClient.loggingDisabled) async throws -> CreateScheduledQueryResponse {
        try await self.client.execute(
            operation: "CreateScheduledQuery", 
            path: "/", 
            httpMethod: .POST, 
            serviceConfig: self.config
                .with(middleware: EndpointDiscoveryMiddleware(storage: self.endpointStorage, discover: self.getEndpoint, required: true)
            ), 
            input: input, 
            logger: logger
        )
    }
    ///  Create a scheduled query that will be run on your behalf at the configured schedule. Timestream assumes the execution role provided as part of the ScheduledQueryExecutionRoleArn parameter to run the query. You can use the NotificationConfiguration parameter to configure notification for your scheduled query operations.
    ///
    /// Parameters:
    ///   - clientToken: Using a ClientToken makes the call to CreateScheduledQuery idempotent, in other words, making the same request repeatedly will produce the same result. Making multiple identical CreateScheduledQuery requests has the same effect as making a single request.    If CreateScheduledQuery is called without a ClientToken, the Query SDK generates a ClientToken on your behalf.   After 8 hours, any request with the same ClientToken is treated as a new request.
    ///   - errorReportConfiguration: Configuration for error reporting. Error reports will be generated when a problem is encountered when writing the query results.
    ///   - kmsKeyId: The Amazon KMS key used to encrypt the scheduled query resource, at-rest. If the Amazon KMS key is not specified, the scheduled query resource will be encrypted with a Timestream owned Amazon KMS key. To specify a KMS key, use the key ID, key ARN, alias name, or alias ARN. When using an alias name, prefix the name with alias/  If ErrorReportConfiguration uses SSE_KMS as encryption type, the same KmsKeyId is used to encrypt the error report at rest.
    ///   - name: Name of the scheduled query.
    ///   - notificationConfiguration: Notification configuration for the scheduled query. A notification is sent by Timestream when a query run finishes, when the state is updated or when you delete it.
    ///   - queryString: The query string to run. Parameter names can be specified in the query string @ character followed by an identifier. The named Parameter @scheduled_runtime is reserved and can be used in the query to get the time at which the query is scheduled to run. The timestamp calculated according to the ScheduleConfiguration parameter, will be the value of @scheduled_runtime paramater for each query run. For example, consider an instance of a scheduled query executing on 2021-12-01 00:00:00. For this instance, the @scheduled_runtime parameter is initialized to the timestamp 2021-12-01 00:00:00 when invoking the query.
    ///   - scheduleConfiguration: The schedule configuration for the query.
    ///   - scheduledQueryExecutionRoleArn: The ARN for the IAM role that Timestream will assume when running the scheduled query.
    ///   - tags: A list of key-value pairs to label the scheduled query.
    ///   - targetConfiguration: Configuration used for writing the result of a query.
    ///   - logger: Logger use during operation
    @inlinable
    public func createScheduledQuery(
        clientToken: String? = CreateScheduledQueryRequest.idempotencyToken(),
        errorReportConfiguration: ErrorReportConfiguration,
        kmsKeyId: String? = nil,
        name: String,
        notificationConfiguration: NotificationConfiguration,
        queryString: String,
        scheduleConfiguration: ScheduleConfiguration,
        scheduledQueryExecutionRoleArn: String,
        tags: [Tag]? = nil,
        targetConfiguration: TargetConfiguration? = nil,
        logger: Logger = AWSClient.loggingDisabled        
    ) async throws -> CreateScheduledQueryResponse {
        let input = CreateScheduledQueryRequest(
            clientToken: clientToken, 
            errorReportConfiguration: errorReportConfiguration, 
            kmsKeyId: kmsKeyId, 
            name: name, 
            notificationConfiguration: notificationConfiguration, 
            queryString: queryString, 
            scheduleConfiguration: scheduleConfiguration, 
            scheduledQueryExecutionRoleArn: scheduledQueryExecutionRoleArn, 
            tags: tags, 
            targetConfiguration: targetConfiguration
        )
        return try await self.createScheduledQuery(input, logger: logger)
    }

    /// Deletes a given scheduled query. This is an irreversible operation.
    @Sendable
    @inlinable
    public func deleteScheduledQuery(_ input: DeleteScheduledQueryRequest, logger: Logger = AWSClient.loggingDisabled) async throws {
        try await self.client.execute(
            operation: "DeleteScheduledQuery", 
            path: "/", 
            httpMethod: .POST, 
            serviceConfig: self.config
                .with(middleware: EndpointDiscoveryMiddleware(storage: self.endpointStorage, discover: self.getEndpoint, required: true)
            ), 
            input: input, 
            logger: logger
        )
    }
    /// Deletes a given scheduled query. This is an irreversible operation.
    ///
    /// Parameters:
    ///   - scheduledQueryArn: The ARN of the scheduled query.
    ///   - logger: Logger use during operation
    @inlinable
    public func deleteScheduledQuery(
        scheduledQueryArn: String,
        logger: Logger = AWSClient.loggingDisabled        
    ) async throws {
        let input = DeleteScheduledQueryRequest(
            scheduledQueryArn: scheduledQueryArn
        )
        return try await self.deleteScheduledQuery(input, logger: logger)
    }

    /// Describes the settings for your account that include the query pricing model and the configured maximum TCUs the service can use for your query workload. You're charged only for the duration of compute units used for your workloads.
    @Sendable
    @inlinable
    public func describeAccountSettings(_ input: DescribeAccountSettingsRequest, logger: Logger = AWSClient.loggingDisabled) async throws -> DescribeAccountSettingsResponse {
        try await self.client.execute(
            operation: "DescribeAccountSettings", 
            path: "/", 
            httpMethod: .POST, 
            serviceConfig: self.config
                .with(middleware: EndpointDiscoveryMiddleware(storage: self.endpointStorage, discover: self.getEndpoint, required: true)
            ), 
            input: input, 
            logger: logger
        )
    }
    /// Describes the settings for your account that include the query pricing model and the configured maximum TCUs the service can use for your query workload. You're charged only for the duration of compute units used for your workloads.
    ///
    /// Parameters:
    ///   - logger: Logger use during operation
    @inlinable
    public func describeAccountSettings(
        logger: Logger = AWSClient.loggingDisabled        
    ) async throws -> DescribeAccountSettingsResponse {
        let input = DescribeAccountSettingsRequest(
        )
        return try await self.describeAccountSettings(input, logger: logger)
    }

    /// DescribeEndpoints returns a list of available endpoints to make Timestream API calls against. This API is available through both Write and Query. Because the Timestream SDKs are designed to transparently work with the service’s architecture, including the management and mapping of the service endpoints, it is not recommended that you use this API unless:   You are using VPC endpoints (Amazon Web Services PrivateLink) with Timestream     Your application uses a programming language that does not yet have SDK support   You require better control over the client-side implementation   For detailed information on how and when to use and implement DescribeEndpoints, see The Endpoint Discovery Pattern.
    @Sendable
    @inlinable
    public func describeEndpoints(_ input: DescribeEndpointsRequest, logger: Logger = AWSClient.loggingDisabled) async throws -> DescribeEndpointsResponse {
        try await self.client.execute(
            operation: "DescribeEndpoints", 
            path: "/", 
            httpMethod: .POST, 
            serviceConfig: self.config, 
            input: input, 
            logger: logger
        )
    }
    /// DescribeEndpoints returns a list of available endpoints to make Timestream API calls against. This API is available through both Write and Query. Because the Timestream SDKs are designed to transparently work with the service’s architecture, including the management and mapping of the service endpoints, it is not recommended that you use this API unless:   You are using VPC endpoints (Amazon Web Services PrivateLink) with Timestream     Your application uses a programming language that does not yet have SDK support   You require better control over the client-side implementation   For detailed information on how and when to use and implement DescribeEndpoints, see The Endpoint Discovery Pattern.
    ///
    /// Parameters:
    ///   - logger: Logger use during operation
    @inlinable
    public func describeEndpoints(
        logger: Logger = AWSClient.loggingDisabled        
    ) async throws -> DescribeEndpointsResponse {
        let input = DescribeEndpointsRequest(
        )
        return try await self.describeEndpoints(input, logger: logger)
    }

    /// Provides detailed information about a scheduled query.
    @Sendable
    @inlinable
    public func describeScheduledQuery(_ input: DescribeScheduledQueryRequest, logger: Logger = AWSClient.loggingDisabled) async throws -> DescribeScheduledQueryResponse {
        try await self.client.execute(
            operation: "DescribeScheduledQuery", 
            path: "/", 
            httpMethod: .POST, 
            serviceConfig: self.config
                .with(middleware: EndpointDiscoveryMiddleware(storage: self.endpointStorage, discover: self.getEndpoint, required: true)
            ), 
            input: input, 
            logger: logger
        )
    }
    /// Provides detailed information about a scheduled query.
    ///
    /// Parameters:
    ///   - scheduledQueryArn: The ARN of the scheduled query.
    ///   - logger: Logger use during operation
    @inlinable
    public func describeScheduledQuery(
        scheduledQueryArn: String,
        logger: Logger = AWSClient.loggingDisabled        
    ) async throws -> DescribeScheduledQueryResponse {
        let input = DescribeScheduledQueryRequest(
            scheduledQueryArn: scheduledQueryArn
        )
        return try await self.describeScheduledQuery(input, logger: logger)
    }

    ///  You can use this API to run a scheduled query manually.  If you enabled QueryInsights, this API also returns insights and metrics related to the query that you executed as part of an Amazon SNS notification. QueryInsights helps with performance tuning of your query. For more information about QueryInsights, see Using query insights to optimize queries in Amazon Timestream.
    @Sendable
    @inlinable
    public func executeScheduledQuery(_ input: ExecuteScheduledQueryRequest, logger: Logger = AWSClient.loggingDisabled) async throws {
        try await self.client.execute(
            operation: "ExecuteScheduledQuery", 
            path: "/", 
            httpMethod: .POST, 
            serviceConfig: self.config
                .with(middleware: EndpointDiscoveryMiddleware(storage: self.endpointStorage, discover: self.getEndpoint, required: true)
            ), 
            input: input, 
            logger: logger
        )
    }
    ///  You can use this API to run a scheduled query manually.  If you enabled QueryInsights, this API also returns insights and metrics related to the query that you executed as part of an Amazon SNS notification. QueryInsights helps with performance tuning of your query. For more information about QueryInsights, see Using query insights to optimize queries in Amazon Timestream.
    ///
    /// Parameters:
    ///   - clientToken: Not used.
    ///   - invocationTime: The timestamp in UTC. Query will be run as if it was invoked at this timestamp.
    ///   - queryInsights: Encapsulates settings for enabling QueryInsights. Enabling QueryInsights returns insights and metrics as a part of the Amazon SNS notification for the query that you executed. You can use QueryInsights to tune your query performance and cost.
    ///   - scheduledQueryArn: ARN of the scheduled query.
    ///   - logger: Logger use during operation
    @inlinable
    public func executeScheduledQuery(
        clientToken: String? = ExecuteScheduledQueryRequest.idempotencyToken(),
        invocationTime: Date,
        queryInsights: ScheduledQueryInsights? = nil,
        scheduledQueryArn: String,
        logger: Logger = AWSClient.loggingDisabled        
    ) async throws {
        let input = ExecuteScheduledQueryRequest(
            clientToken: clientToken, 
            invocationTime: invocationTime, 
            queryInsights: queryInsights, 
            scheduledQueryArn: scheduledQueryArn
        )
        return try await self.executeScheduledQuery(input, logger: logger)
    }

    /// Gets a list of all scheduled queries in the caller's Amazon account and Region. ListScheduledQueries is eventually consistent.
    @Sendable
    @inlinable
    public func listScheduledQueries(_ input: ListScheduledQueriesRequest, logger: Logger = AWSClient.loggingDisabled) async throws -> ListScheduledQueriesResponse {
        try await self.client.execute(
            operation: "ListScheduledQueries", 
            path: "/", 
            httpMethod: .POST, 
            serviceConfig: self.config
                .with(middleware: EndpointDiscoveryMiddleware(storage: self.endpointStorage, discover: self.getEndpoint, required: true)
            ), 
            input: input, 
            logger: logger
        )
    }
    /// Gets a list of all scheduled queries in the caller's Amazon account and Region. ListScheduledQueries is eventually consistent.
    ///
    /// Parameters:
    ///   - maxResults: The maximum number of items to return in the output. If the total number of items available is more than the value specified, a NextToken is provided in the output. To resume pagination, provide the NextToken value as the argument to the subsequent call to ListScheduledQueriesRequest.
    ///   - nextToken:  A pagination token to resume pagination.
    ///   - logger: Logger use during operation
    @inlinable
    public func listScheduledQueries(
        maxResults: Int? = nil,
        nextToken: String? = nil,
        logger: Logger = AWSClient.loggingDisabled        
    ) async throws -> ListScheduledQueriesResponse {
        let input = ListScheduledQueriesRequest(
            maxResults: maxResults, 
            nextToken: nextToken
        )
        return try await self.listScheduledQueries(input, logger: logger)
    }

    /// List all tags on a Timestream query resource.
    @Sendable
    @inlinable
    public func listTagsForResource(_ input: ListTagsForResourceRequest, logger: Logger = AWSClient.loggingDisabled) async throws -> ListTagsForResourceResponse {
        try await self.client.execute(
            operation: "ListTagsForResource", 
            path: "/", 
            httpMethod: .POST, 
            serviceConfig: self.config
                .with(middleware: EndpointDiscoveryMiddleware(storage: self.endpointStorage, discover: self.getEndpoint, required: true)
            ), 
            input: input, 
            logger: logger
        )
    }
    /// List all tags on a Timestream query resource.
    ///
    /// Parameters:
    ///   - maxResults: The maximum number of tags to return.
    ///   - nextToken: A pagination token to resume pagination.
    ///   - resourceARN: The Timestream resource with tags to be listed. This value is an Amazon Resource Name (ARN).
    ///   - logger: Logger use during operation
    @inlinable
    public func listTagsForResource(
        maxResults: Int? = nil,
        nextToken: String? = nil,
        resourceARN: String,
        logger: Logger = AWSClient.loggingDisabled        
    ) async throws -> ListTagsForResourceResponse {
        let input = ListTagsForResourceRequest(
            maxResults: maxResults, 
            nextToken: nextToken, 
            resourceARN: resourceARN
        )
        return try await self.listTagsForResource(input, logger: logger)
    }

    /// A synchronous operation that allows you to submit a query with parameters to be stored by Timestream for later running. Timestream only supports using this operation with ValidateOnly set to true.
    @Sendable
    @inlinable
    public func prepareQuery(_ input: PrepareQueryRequest, logger: Logger = AWSClient.loggingDisabled) async throws -> PrepareQueryResponse {
        try await self.client.execute(
            operation: "PrepareQuery", 
            path: "/", 
            httpMethod: .POST, 
            serviceConfig: self.config
                .with(middleware: EndpointDiscoveryMiddleware(storage: self.endpointStorage, discover: self.getEndpoint, required: true)
            ), 
            input: input, 
            logger: logger
        )
    }
    /// A synchronous operation that allows you to submit a query with parameters to be stored by Timestream for later running. Timestream only supports using this operation with ValidateOnly set to true.
    ///
    /// Parameters:
    ///   - queryString: The Timestream query string that you want to use as a prepared statement. Parameter names can be specified in the query string @ character followed by an identifier.
    ///   - validateOnly: By setting this value to true, Timestream will only validate that the query string is a valid Timestream query, and not store the prepared query for later use.
    ///   - logger: Logger use during operation
    @inlinable
    public func prepareQuery(
        queryString: String,
        validateOnly: Bool? = nil,
        logger: Logger = AWSClient.loggingDisabled        
    ) async throws -> PrepareQueryResponse {
        let input = PrepareQueryRequest(
            queryString: queryString, 
            validateOnly: validateOnly
        )
        return try await self.prepareQuery(input, logger: logger)
    }

    ///  Query is a synchronous operation that enables you to run a query against your Amazon Timestream data. If you enabled QueryInsights, this API also returns insights and metrics related to the query that you executed. QueryInsights helps with performance tuning of your query. For more information about QueryInsights, see Using query insights to optimize queries in Amazon Timestream.  The maximum number of Query API requests you're allowed to make with QueryInsights enabled is 1 query per second (QPS). If you exceed this query rate, it might result in throttling.   Query will time out after 60 seconds. You must update the default timeout in the SDK to support a timeout of 60 seconds. See the code sample for details.  Your query request will fail in the following cases:   If you submit a Query request with the same client token outside of the 5-minute idempotency window.    If you submit a Query request with the same client token, but change other parameters, within the 5-minute idempotency window.    If the size of the row (including the query metadata) exceeds 1 MB, then the query will fail with the following error message:   Query aborted as max page response size has been exceeded by the output result row    If the IAM principal of the query initiator and the result reader are not the same and/or the query initiator and the result reader do not have the same query string in the query requests, the query will fail with an Invalid pagination token error.
    @Sendable
    @inlinable
    public func query(_ input: QueryRequest, logger: Logger = AWSClient.loggingDisabled) async throws -> QueryResponse {
        try await self.client.execute(
            operation: "Query", 
            path: "/", 
            httpMethod: .POST, 
            serviceConfig: self.config
                .with(middleware: EndpointDiscoveryMiddleware(storage: self.endpointStorage, discover: self.getEndpoint, required: true)
            ), 
            input: input, 
            logger: logger
        )
    }
    ///  Query is a synchronous operation that enables you to run a query against your Amazon Timestream data. If you enabled QueryInsights, this API also returns insights and metrics related to the query that you executed. QueryInsights helps with performance tuning of your query. For more information about QueryInsights, see Using query insights to optimize queries in Amazon Timestream.  The maximum number of Query API requests you're allowed to make with QueryInsights enabled is 1 query per second (QPS). If you exceed this query rate, it might result in throttling.   Query will time out after 60 seconds. You must update the default timeout in the SDK to support a timeout of 60 seconds. See the code sample for details.  Your query request will fail in the following cases:   If you submit a Query request with the same client token outside of the 5-minute idempotency window.    If you submit a Query request with the same client token, but change other parameters, within the 5-minute idempotency window.    If the size of the row (including the query metadata) exceeds 1 MB, then the query will fail with the following error message:   Query aborted as max page response size has been exceeded by the output result row    If the IAM principal of the query initiator and the result reader are not the same and/or the query initiator and the result reader do not have the same query string in the query requests, the query will fail with an Invalid pagination token error.
    ///
    /// Parameters:
    ///   - clientToken:  Unique, case-sensitive string of up to 64 ASCII characters specified when a Query request is made. Providing a ClientToken makes the call to Query idempotent. This means that running the same query repeatedly will produce the same result. In other words, making multiple identical Query requests has the same effect as making a single request. When using ClientToken in a query, note the following:    If the Query API is instantiated without a ClientToken, the Query SDK generates a ClientToken on your behalf.   If the Query invocation only contains the ClientToken but does not include a NextToken, that invocation of Query is assumed to be a new query run.   If the invocation contains NextToken, that particular invocation is assumed to be a subsequent invocation of a prior call to the Query API, and a result set is returned.   After 4 hours, any request with the same ClientToken is treated as a new request.
    ///   - maxRows:  The total number of rows to be returned in the Query output. The initial run of Query with a MaxRows value specified will return the result set of the query in two cases:    The size of the result is less than 1MB.   The number of rows in the result set is less than the value of maxRows.   Otherwise, the initial invocation of Query only returns a NextToken, which can then be used in subsequent calls to fetch the result set. To resume pagination, provide the NextToken value in the subsequent command. If the row size is large (e.g. a row has many columns), Timestream may return fewer rows to keep the response size from exceeding the 1 MB limit. If MaxRows is not provided, Timestream will send the necessary number of rows to meet the 1 MB limit.
    ///   - nextToken:  A pagination token used to return a set of results. When the Query API is invoked using NextToken, that particular invocation is assumed to be a subsequent invocation of a prior call to Query, and a result set is returned. However, if the Query invocation only contains the ClientToken, that invocation of Query is assumed to be a new query run.  Note the following when using NextToken in a query:   A pagination token can be used for up to five Query invocations, OR for a duration of up to 1 hour – whichever comes first.   Using the same NextToken will return the same set of records. To keep paginating through the result set, you must to use the most recent nextToken.   Suppose a Query invocation returns two NextToken values, TokenA and TokenB. If TokenB is used in a subsequent Query invocation, then TokenA is invalidated and cannot be reused.   To request a previous result set from a query after pagination has begun, you must re-invoke the Query API.   The latest NextToken should be used to paginate until null is returned, at which point a new NextToken should be used.   If the IAM principal of the query initiator and the result reader are not the same and/or the query initiator and the result reader do not have the same query string in the query requests, the query will fail with an Invalid pagination token error.
    ///   - queryInsights: Encapsulates settings for enabling QueryInsights. Enabling QueryInsights returns insights and metrics in addition to query results for the query that you executed. You can use QueryInsights to tune your query performance.
    ///   - queryString:  The query to be run by Timestream.
    ///   - logger: Logger use during operation
    @inlinable
    public func query(
        clientToken: String? = QueryRequest.idempotencyToken(),
        maxRows: Int? = nil,
        nextToken: String? = nil,
        queryInsights: QueryInsights? = nil,
        queryString: String,
        logger: Logger = AWSClient.loggingDisabled        
    ) async throws -> QueryResponse {
        let input = QueryRequest(
            clientToken: clientToken, 
            maxRows: maxRows, 
            nextToken: nextToken, 
            queryInsights: queryInsights, 
            queryString: queryString
        )
        return try await self.query(input, logger: logger)
    }

    /// Associate a set of tags with a Timestream resource. You can then activate these user-defined tags so that they appear on the Billing and Cost Management console for cost allocation tracking.
    @Sendable
    @inlinable
    public func tagResource(_ input: TagResourceRequest, logger: Logger = AWSClient.loggingDisabled) async throws -> TagResourceResponse {
        try await self.client.execute(
            operation: "TagResource", 
            path: "/", 
            httpMethod: .POST, 
            serviceConfig: self.config
                .with(middleware: EndpointDiscoveryMiddleware(storage: self.endpointStorage, discover: self.getEndpoint, required: true)
            ), 
            input: input, 
            logger: logger
        )
    }
    /// Associate a set of tags with a Timestream resource. You can then activate these user-defined tags so that they appear on the Billing and Cost Management console for cost allocation tracking.
    ///
    /// Parameters:
    ///   - resourceARN: Identifies the Timestream resource to which tags should be added. This value is an Amazon Resource Name (ARN).
    ///   - tags: The tags to be assigned to the Timestream resource.
    ///   - logger: Logger use during operation
    @inlinable
    public func tagResource(
        resourceARN: String,
        tags: [Tag],
        logger: Logger = AWSClient.loggingDisabled        
    ) async throws -> TagResourceResponse {
        let input = TagResourceRequest(
            resourceARN: resourceARN, 
            tags: tags
        )
        return try await self.tagResource(input, logger: logger)
    }

    /// Removes the association of tags from a Timestream query resource.
    @Sendable
    @inlinable
    public func untagResource(_ input: UntagResourceRequest, logger: Logger = AWSClient.loggingDisabled) async throws -> UntagResourceResponse {
        try await self.client.execute(
            operation: "UntagResource", 
            path: "/", 
            httpMethod: .POST, 
            serviceConfig: self.config
                .with(middleware: EndpointDiscoveryMiddleware(storage: self.endpointStorage, discover: self.getEndpoint, required: true)
            ), 
            input: input, 
            logger: logger
        )
    }
    /// Removes the association of tags from a Timestream query resource.
    ///
    /// Parameters:
    ///   - resourceARN: The Timestream resource that the tags will be removed from. This value is an Amazon Resource Name (ARN).
    ///   - tagKeys: A list of tags keys. Existing tags of the resource whose keys are members of this list will be removed from the Timestream resource.
    ///   - logger: Logger use during operation
    @inlinable
    public func untagResource(
        resourceARN: String,
        tagKeys: [String],
        logger: Logger = AWSClient.loggingDisabled        
    ) async throws -> UntagResourceResponse {
        let input = UntagResourceRequest(
            resourceARN: resourceARN, 
            tagKeys: tagKeys
        )
        return try await self.untagResource(input, logger: logger)
    }

    /// Transitions your account to use TCUs for query pricing and modifies the maximum query compute units that you've configured. If you reduce the value of MaxQueryTCU to a desired configuration, the new value can take up to 24 hours to be effective.  After you've transitioned your account to use TCUs for query pricing, you can't transition to using bytes scanned for query pricing.
    @Sendable
    @inlinable
    public func updateAccountSettings(_ input: UpdateAccountSettingsRequest, logger: Logger = AWSClient.loggingDisabled) async throws -> UpdateAccountSettingsResponse {
        try await self.client.execute(
            operation: "UpdateAccountSettings", 
            path: "/", 
            httpMethod: .POST, 
            serviceConfig: self.config
                .with(middleware: EndpointDiscoveryMiddleware(storage: self.endpointStorage, discover: self.getEndpoint, required: true)
            ), 
            input: input, 
            logger: logger
        )
    }
    /// Transitions your account to use TCUs for query pricing and modifies the maximum query compute units that you've configured. If you reduce the value of MaxQueryTCU to a desired configuration, the new value can take up to 24 hours to be effective.  After you've transitioned your account to use TCUs for query pricing, you can't transition to using bytes scanned for query pricing.
    ///
    /// Parameters:
    ///   - maxQueryTCU: The maximum number of compute units the service will use at any point in time to serve your queries. To run queries, you must set a minimum capacity of 4 TCU. You can set the maximum number of TCU in multiples of 4, for example, 4, 8, 16, 32, and so on. The maximum value supported for MaxQueryTCU is 1000. To request an increase to this soft limit, contact Amazon Web Services Support. For information about the default quota for maxQueryTCU, see Default quotas. This configuration is applicable only for on-demand usage of Timestream Compute Units (TCUs). The maximum value supported for MaxQueryTCU is 1000. To request an increase to this soft limit, contact Amazon Web Services Support. For information about the default quota for maxQueryTCU, see Default quotas.
    ///   - queryCompute: Modifies the query compute settings configured in your account, including the query pricing model and provisioned Timestream Compute Units (TCUs) in your account.  This API is idempotent, meaning that making the same request multiple times will have the same effect as making the request once.
    ///   - queryPricingModel: The pricing model for queries in an account.  The QueryPricingModel parameter is used by several Timestream operations; however, the UpdateAccountSettings API operation doesn't recognize any values other than COMPUTE_UNITS.
    ///   - logger: Logger use during operation
    @inlinable
    public func updateAccountSettings(
        maxQueryTCU: Int? = nil,
        queryCompute: QueryComputeRequest? = nil,
        queryPricingModel: QueryPricingModel? = nil,
        logger: Logger = AWSClient.loggingDisabled        
    ) async throws -> UpdateAccountSettingsResponse {
        let input = UpdateAccountSettingsRequest(
            maxQueryTCU: maxQueryTCU, 
            queryCompute: queryCompute, 
            queryPricingModel: queryPricingModel
        )
        return try await self.updateAccountSettings(input, logger: logger)
    }

    /// Update a scheduled query.
    @Sendable
    @inlinable
    public func updateScheduledQuery(_ input: UpdateScheduledQueryRequest, logger: Logger = AWSClient.loggingDisabled) async throws {
        try await self.client.execute(
            operation: "UpdateScheduledQuery", 
            path: "/", 
            httpMethod: .POST, 
            serviceConfig: self.config
                .with(middleware: EndpointDiscoveryMiddleware(storage: self.endpointStorage, discover: self.getEndpoint, required: true)
            ), 
            input: input, 
            logger: logger
        )
    }
    /// Update a scheduled query.
    ///
    /// Parameters:
    ///   - scheduledQueryArn: ARN of the scheuled query.
    ///   - state: State of the scheduled query.
    ///   - logger: Logger use during operation
    @inlinable
    public func updateScheduledQuery(
        scheduledQueryArn: String,
        state: ScheduledQueryState,
        logger: Logger = AWSClient.loggingDisabled        
    ) async throws {
        let input = UpdateScheduledQueryRequest(
            scheduledQueryArn: scheduledQueryArn, 
            state: state
        )
        return try await self.updateScheduledQuery(input, logger: logger)
    }

    @Sendable 
    @usableFromInline 
    func getEndpoint(logger: Logger) async throws -> AWSEndpoints {
        let response = try await self.describeEndpoints(.init(), logger: logger)
        return .init(endpoints: response.endpoints.map {
            .init(address: "https://\($0.address)", cachePeriodInMinutes: $0.cachePeriodInMinutes)
        })
    }
}

extension TimestreamQuery {
    /// Initializer required by `AWSService.with(middlewares:timeout:byteBufferAllocator:options)`. You are not able to use this initializer directly as there are not public
    /// initializers for `AWSServiceConfig.Patch`. Please use `AWSService.with(middlewares:timeout:byteBufferAllocator:options)` instead.
    public init(from: TimestreamQuery, patch: AWSServiceConfig.Patch) {
        self.client = from.client
        self.config = from.config.with(patch: patch)
        self.endpointStorage = .init()
    }
}

// MARK: Paginators

@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
extension TimestreamQuery {
    /// Return PaginatorSequence for operation ``listScheduledQueries(_:logger:)``.
    ///
    /// - Parameters:
    ///   - input: Input for operation
    ///   - logger: Logger used for logging
    @inlinable
    public func listScheduledQueriesPaginator(
        _ input: ListScheduledQueriesRequest,
        logger: Logger = AWSClient.loggingDisabled
    ) -> AWSClient.PaginatorSequence<ListScheduledQueriesRequest, ListScheduledQueriesResponse> {
        return .init(
            input: input,
            command: self.listScheduledQueries,
            inputKey: \ListScheduledQueriesRequest.nextToken,
            outputKey: \ListScheduledQueriesResponse.nextToken,
            logger: logger
        )
    }
    /// Return PaginatorSequence for operation ``listScheduledQueries(_:logger:)``.
    ///
    /// - Parameters:
    ///   - maxResults: The maximum number of items to return in the output. If the total number of items available is more than the value specified, a NextToken is provided in the output. To resume pagination, provide the NextToken value as the argument to the subsequent call to ListScheduledQueriesRequest.
    ///   - logger: Logger used for logging
    @inlinable
    public func listScheduledQueriesPaginator(
        maxResults: Int? = nil,
        logger: Logger = AWSClient.loggingDisabled        
    ) -> AWSClient.PaginatorSequence<ListScheduledQueriesRequest, ListScheduledQueriesResponse> {
        let input = ListScheduledQueriesRequest(
            maxResults: maxResults
        )
        return self.listScheduledQueriesPaginator(input, logger: logger)
    }

    /// Return PaginatorSequence for operation ``listTagsForResource(_:logger:)``.
    ///
    /// - Parameters:
    ///   - input: Input for operation
    ///   - logger: Logger used for logging
    @inlinable
    public func listTagsForResourcePaginator(
        _ input: ListTagsForResourceRequest,
        logger: Logger = AWSClient.loggingDisabled
    ) -> AWSClient.PaginatorSequence<ListTagsForResourceRequest, ListTagsForResourceResponse> {
        return .init(
            input: input,
            command: self.listTagsForResource,
            inputKey: \ListTagsForResourceRequest.nextToken,
            outputKey: \ListTagsForResourceResponse.nextToken,
            logger: logger
        )
    }
    /// Return PaginatorSequence for operation ``listTagsForResource(_:logger:)``.
    ///
    /// - Parameters:
    ///   - maxResults: The maximum number of tags to return.
    ///   - resourceARN: The Timestream resource with tags to be listed. This value is an Amazon Resource Name (ARN).
    ///   - logger: Logger used for logging
    @inlinable
    public func listTagsForResourcePaginator(
        maxResults: Int? = nil,
        resourceARN: String,
        logger: Logger = AWSClient.loggingDisabled        
    ) -> AWSClient.PaginatorSequence<ListTagsForResourceRequest, ListTagsForResourceResponse> {
        let input = ListTagsForResourceRequest(
            maxResults: maxResults, 
            resourceARN: resourceARN
        )
        return self.listTagsForResourcePaginator(input, logger: logger)
    }

    /// Return PaginatorSequence for operation ``query(_:logger:)``.
    ///
    /// - Parameters:
    ///   - input: Input for operation
    ///   - logger: Logger used for logging
    @inlinable
    public func queryPaginator(
        _ input: QueryRequest,
        logger: Logger = AWSClient.loggingDisabled
    ) -> AWSClient.PaginatorSequence<QueryRequest, QueryResponse> {
        return .init(
            input: input,
            command: self.query,
            inputKey: \QueryRequest.nextToken,
            outputKey: \QueryResponse.nextToken,
            logger: logger
        )
    }
    /// Return PaginatorSequence for operation ``query(_:logger:)``.
    ///
    /// - Parameters:
    ///   - clientToken:  Unique, case-sensitive string of up to 64 ASCII characters specified when a Query request is made. Providing a ClientToken makes the call to Query idempotent. This means that running the same query repeatedly will produce the same result. In other words, making multiple identical Query requests has the same effect as making a single request. When using ClientToken in a query, note the following:    If the Query API is instantiated without a ClientToken, the Query SDK generates a ClientToken on your behalf.   If the Query invocation only contains the ClientToken but does not include a NextToken, that invocation of Query is assumed to be a new query run.   If the invocation contains NextToken, that particular invocation is assumed to be a subsequent invocation of a prior call to the Query API, and a result set is returned.   After 4 hours, any request with the same ClientToken is treated as a new request.
    ///   - maxRows:  The total number of rows to be returned in the Query output. The initial run of Query with a MaxRows value specified will return the result set of the query in two cases:    The size of the result is less than 1MB.   The number of rows in the result set is less than the value of maxRows.   Otherwise, the initial invocation of Query only returns a NextToken, which can then be used in subsequent calls to fetch the result set. To resume pagination, provide the NextToken value in the subsequent command. If the row size is large (e.g. a row has many columns), Timestream may return fewer rows to keep the response size from exceeding the 1 MB limit. If MaxRows is not provided, Timestream will send the necessary number of rows to meet the 1 MB limit.
    ///   - queryInsights: Encapsulates settings for enabling QueryInsights. Enabling QueryInsights returns insights and metrics in addition to query results for the query that you executed. You can use QueryInsights to tune your query performance.
    ///   - queryString:  The query to be run by Timestream.
    ///   - logger: Logger used for logging
    @inlinable
    public func queryPaginator(
        clientToken: String? = QueryRequest.idempotencyToken(),
        maxRows: Int? = nil,
        queryInsights: QueryInsights? = nil,
        queryString: String,
        logger: Logger = AWSClient.loggingDisabled        
    ) -> AWSClient.PaginatorSequence<QueryRequest, QueryResponse> {
        let input = QueryRequest(
            clientToken: clientToken, 
            maxRows: maxRows, 
            queryInsights: queryInsights, 
            queryString: queryString
        )
        return self.queryPaginator(input, logger: logger)
    }
}

extension TimestreamQuery.ListScheduledQueriesRequest: AWSPaginateToken {
    @inlinable
    public func usingPaginationToken(_ token: String) -> TimestreamQuery.ListScheduledQueriesRequest {
        return .init(
            maxResults: self.maxResults,
            nextToken: token
        )
    }
}

extension TimestreamQuery.ListTagsForResourceRequest: AWSPaginateToken {
    @inlinable
    public func usingPaginationToken(_ token: String) -> TimestreamQuery.ListTagsForResourceRequest {
        return .init(
            maxResults: self.maxResults,
            nextToken: token,
            resourceARN: self.resourceARN
        )
    }
}

extension TimestreamQuery.QueryRequest: AWSPaginateToken {
    @inlinable
    public func usingPaginationToken(_ token: String) -> TimestreamQuery.QueryRequest {
        return .init(
            clientToken: self.clientToken,
            maxRows: self.maxRows,
            nextToken: token,
            queryInsights: self.queryInsights,
            queryString: self.queryString
        )
    }
}
